%%%-------------------------------------------------------------------
%%% @author wukai
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 22. 十二月 2017 17:57
%%%-------------------------------------------------------------------
-module(device_hub).
-author("wukai").

-behaviour(gen_server).
-export([start_link/0]).
-export([init/1,
  handle_call/3,
  handle_cast/2,
  handle_info/2,
  terminate/2,
  code_change/3]).

-define(SERVER, ?MODULE).
-record(state, {}).

start_link() ->
  gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

init([]) ->
  subscribe_server:send_sub([{<<"cbd/sys/publish/order/start">>,1}], {"admin","system_subscriber"}, self()),
{ok, #state{}}.

handle_call(_Request, _From, State) ->
  {reply, ok, State}.

handle_cast(_Request, State) ->
  {noreply, State}.

handle_info({publish,Publish},State) ->
  Content = publish_frame:content(Publish),
  log:log("content:~p",[Content]),
  Json = jsx:decode(Content),
  [{<<"order_sn">>,_},
    {<<"device_sn">>,ClientId},
    {<<"port">>,_},{<<"user">>,Username}]= Json,
  session_server:publish({Username,ClientId},Publish),
  {noreply, State};

handle_info(_Info, State) ->
  {noreply, State}.
terminate(_Reason, _State) ->
  ok.
code_change(_OldVsn, State, _Extra) ->
  {ok, State}.
